<?php

/**
 * WordPress 文章导入 RSS 生成脚本 (最终版)
 * 生成完全符合 WordPress 导出标准的 WXR 格式
 */

class WordPressRSSGenerator
{
    private $siteUrl;
    private $siteTitle;
    private $siteDescription;
    private $items = [];
    private $authors = [];
    private $categories = [];
    private $tags = [];

    public function __construct($siteUrl, $siteTitle, $siteDescription)
    {
        $this->siteUrl = rtrim($siteUrl, '/');
        $this->siteTitle = $siteTitle;
        $this->siteDescription = $siteDescription;
    }

    /**
     * 添加作者
     */
    public function addAuthor($login, $email, $display_name = '', $first_name = '', $last_name = '')
    {
        $this->authors[$login] = [
            'login' => $login,
            'email' => $email,
            'display_name' => $display_name ?: $login,
            'first_name' => $first_name,
            'last_name' => $last_name
        ];
    }

    /**
     * 添加分类
     */
    public function addCategory($name, $slug = '', $description = '', $parent = '')
    {
        $slug = $slug ?: sanitize_title($name);
        $this->categories[$slug] = [
            'term_id' => count($this->categories) + 1,
            'name' => $name,
            'slug' => $slug,
            'description' => $description,
            'parent' => $parent
        ];
    }

    /**
     * 添加标签
     */
    public function addTag($name, $slug = '', $description = '')
    {
        $slug = $slug ?: sanitize_title($name);
        $this->tags[$slug] = [
            'term_id' => count($this->tags) + 1,
            'name' => $name,
            'slug' => $slug,
            'description' => $description
        ];
    }

    /**
     * 添加文章项
     */
    public function addItem($title, $content, $excerpt = '', $categories = [], $tags = [], $pubDate = null, $author = 'admin', $status = 'publish', $comment_status = 'open', $ping_status = 'open')
    {
        if ($pubDate === null) {
            $pubDate = date('r');
        } elseif (is_numeric($pubDate)) {
            $pubDate = date('r', $pubDate);
        }

        $this->items[] = [
            'title' => $title,
            'content' => $content,
            'excerpt' => $excerpt,
            'categories' => $categories,
            'tags' => $tags,
            'pubDate' => $pubDate,
            'author' => $author,
            'status' => $status,
            'comment_status' => $comment_status,
            'ping_status' => $ping_status,
            'guid' => $this->siteUrl . '/?p=' . (count($this->items) + 1),
            'post_name' => sanitize_title($title)
        ];
    }


    /**
     * 生成 RSS XML
     */
    public function generate()
    {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $dom->formatOutput = true;

        // 创建根元素
        $rss = $dom->createElement('rss');
        $rss->setAttribute('version', '2.0');
        $rss->setAttribute('xmlns:excerpt', 'http://wordpress.org/export/1.2/excerpt/');
        $rss->setAttribute('xmlns:content', 'http://purl.org/rss/1.0/modules/content/');
        $rss->setAttribute('xmlns:wfw', 'http://wellformedweb.org/CommentAPI/');
        $rss->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
        $rss->setAttribute('xmlns:wp', 'http://wordpress.org/export/1.2/');
        $dom->appendChild($rss);

        // 创建channel元素
        $channel = $dom->createElement('channel');
        $rss->appendChild($channel);

        // 添加生成器信息
        $generatorComment = $dom->createComment(' generator="WordPress/6.8.1" created="' . date('Y-m-d H:i') . '" ');
        $channel->appendChild($generatorComment);

        // 添加基本频道信息
        $this->addChildElement($channel, 'title', $this->siteTitle);
        $this->addChildElement($channel, 'link', $this->siteUrl);
        $this->addChildElement($channel, 'description', $this->siteDescription);
        $this->addChildElement($channel, 'pubDate', date('r'));
        $this->addChildElement($channel, 'language', 'zh-CN');
        $this->addChildElement($channel, 'wp:wxr_version', '1.2');
        $this->addChildElement($channel, 'wp:base_site_url', $this->siteUrl);
        $this->addChildElement($channel, 'wp:base_blog_url', $this->siteUrl);

        // 添加作者信息
        foreach ($this->authors as $author) {
            $authorNode = $dom->createElement('wp:author');
            $this->addChildElement($authorNode, 'wp:author_login', $author['login']);
            $this->addChildElement($authorNode, 'wp:author_email', $author['email']);
            $this->addChildElement($authorNode, 'wp:author_display_name', $author['display_name']);
            $this->addChildElement($authorNode, 'wp:author_first_name', $author['first_name']);
            $this->addChildElement($authorNode, 'wp:author_last_name', $author['last_name']);
            $channel->appendChild($authorNode);
        }

        // 添加分类信息
        foreach ($this->categories as $category) {
            $categoryNode = $dom->createElement('wp:category');
            $this->addChildElement($categoryNode, 'wp:term_id', $category['term_id']);
            $this->addChildElement($categoryNode, 'wp:category_nicename', $category['slug']);
            $this->addChildElement($categoryNode, 'wp:category_parent', $category['parent']);
            $this->addCdataChild($categoryNode, 'wp:cat_name', $category['name']);
            $this->addCdataChild($categoryNode, 'wp:category_description', $category['description']);
            $channel->appendChild($categoryNode);
        }

        // 添加标签信息
        foreach ($this->tags as $tag) {
            $tagNode = $dom->createElement('wp:tag');
            $this->addChildElement($tagNode, 'wp:term_id', $tag['term_id']);
            $this->addChildElement($tagNode, 'wp:tag_slug', $tag['slug']);
            $this->addCdataChild($tagNode, 'wp:tag_name', $tag['name']);
            $this->addCdataChild($tagNode, 'wp:tag_description', $tag['description']);
            $channel->appendChild($tagNode);
        }

        // 添加文章项
        foreach ($this->items as $index => $item) {
            $itemNode = $dom->createElement('item');

            $this->addChildElement($itemNode, 'title', $item['title']);
            $this->addChildElement($itemNode, 'link', $item['guid']);
            $this->addChildElement($itemNode, 'pubDate', $item['pubDate']);
            $this->addChildElement($itemNode, 'dc:creator', $item['author']);

            $guid = $dom->createElement('guid', $item['guid']);
            $guid->setAttribute('isPermaLink', 'false');
            $itemNode->appendChild($guid);

          
            foreach ($item['categories'] as $category) {
                $categoryNode = $dom->createElement('category', $category['name'] ?? $category['nicename']);
                $categoryNode->setAttribute('domain', 'category');
                $categoryNode->setAttribute('nicename', $category['nicename']);
                $itemNode->appendChild($categoryNode);
            }

            // 添加标签
            foreach ($item['tags'] as $tag) {
                $tagNode = $dom->createElement('category', $tag);
                $tagNode->setAttribute('domain', 'post_tag');
                $tagNode->setAttribute('nicename', sanitize_title($tag));
                $itemNode->appendChild($tagNode);
            }

            // 添加内容
            $this->addCdataChild($itemNode, 'content:encoded', $item['content']);

            // 添加摘要
            if (!empty($item['excerpt'])) {
                $this->addCdataChild($itemNode, 'excerpt:encoded', $item['excerpt']);
            }

            // WordPress 特定字段
            $this->addChildElement($itemNode, 'wp:post_id', $index + 1);
            $this->addChildElement($itemNode, 'wp:post_date', date('Y-m-d H:i:s', strtotime($item['pubDate'])));
            $this->addChildElement($itemNode, 'wp:post_date_gmt', gmdate('Y-m-d H:i:s', strtotime($item['pubDate'])));
            $this->addChildElement($itemNode, 'wp:comment_status', $item['comment_status']);
            $this->addChildElement($itemNode, 'wp:ping_status', $item['ping_status']);
            $this->addChildElement($itemNode, 'wp:post_name', $item['post_name']);
            $this->addChildElement($itemNode, 'wp:status', $item['status']);
            $this->addChildElement($itemNode, 'wp:post_parent', '0');
            $this->addChildElement($itemNode, 'wp:menu_order', '0');
            $this->addChildElement($itemNode, 'wp:post_type', 'post');
            $this->addChildElement($itemNode, 'wp:post_password', '');
            $this->addChildElement($itemNode, 'wp:is_sticky', '0');

            $channel->appendChild($itemNode);
        }

        return $dom->saveXML();
    }

    /**
     * 保存 RSS 到文件
     */
    public function saveToFile($filename)
    {
        $xml = $this->generate();
        file_put_contents($filename, $xml);
    }

    // 辅助方法：添加子元素
    private function addChildElement($parent, $name, $value)
    {
        $dom = $parent->ownerDocument;
        $child = $dom->createElement($name, htmlspecialchars($value));
        $parent->appendChild($child);
        return $child;
    }

    // 辅助方法：添加CDATA子元素
    private function addCdataChild($parent, $name, $value)
    {
        $dom = $parent->ownerDocument;
        $child = $dom->createElement($name);
        $child->appendChild($dom->createCDATASection($value));
        $parent->appendChild($child);
        return $child;
    }

    // 辅助方法：添加注释
    private function addComment($parent, $comment)
    {
        $dom = $parent->ownerDocument;
        $commentNode = $dom->createComment(' ' . $comment . ' ');
        $parent->appendChild($commentNode);
    }
}
class TxtFileProcessor
{
    public static function scanTxtFiles($directory)
    {
        $txtFiles = [];
        if (!is_dir($directory)) {
            return $txtFiles;
        }
        $items = scandir($directory);

        foreach ($items as $item) {
            if ($item === '.' || $item === '..') {
                continue;
            }
            $path = $directory . DIRECTORY_SEPARATOR . $item;
            if (is_dir($path)) {
                $txtFiles = array_merge($txtFiles, self::scanTxtFiles($path));
            } elseif (is_file($path) && pathinfo($path, PATHINFO_EXTENSION) === 'txt' && mb_strlen(trim($item, '.txt')) > 5) {
                $txtFiles[] = [
                    'title' => $item,
                    'path' => $path
                ];
            }
        }
        return $txtFiles;
    }

    public static function processTxtFiles($directory, $outputDir, $cats = [], $chunkSize = 5000)
    {
        $txtFiles = self::scanTxtFiles($directory);
        $txtFiles = array_chunk($txtFiles, $chunkSize);

        if (!is_dir($outputDir)) {
            mkdir($outputDir, 0777, true);
        }
        if (is_dir($outputDir)) {
            $files = scandir($outputDir);
            foreach ($files as $file) {
                if ($file !== '.' && $file !== '..') {
                    $filePath = $outputDir . DIRECTORY_SEPARATOR . $file;
                    if (is_file($filePath)) {
                        unlink($filePath);
                    }
                }
            }
        }

        $imgs = array_slice(scandir(__DIR__ . "/../uploads/imgs"), 2);
        foreach ($txtFiles as $k => $items) {
            $filePath = $outputDir . DIRECTORY_SEPARATOR . date("Ymd-{$k}") . time() . '.xml';
            if (file_exists($filePath)) {
                unlink($filePath);
            }
            $rssGenerator = new WordPressRSSGenerator(
                'https://gitee.com/xiongzaixxx',
                'free wordpress template',
                'free wordpress template by xiongzai'
            );

            foreach ($items as $i => $item) {
                $content = file_get_contents($item['path']);
                $content = trim(preg_replace('/[\r\n\t]+/', '', $content));
                $content = preg_replace('/<a[^>]*>(.*?)<\/a>/i', '', $content);
                $content = preg_replace('/<img[^>]*>/i', '', $content);

                $title =  trim($item['title'], '.txt');

                $randomImgs = array_rand($imgs, 3);
                $contentParts = explode('</p>', $content);
                $modifiedContent = '';
                foreach ($contentParts as $index => $part) {
                    $modifiedContent .= $part . '</p>';
                    if ($index < 3) {
                        $modifiedContent .= '<img src="/wp-content/uploads/imgs/' . htmlspecialchars($imgs[$randomImgs[$index]]) . '" title="{$title}" />' . PHP_EOL;
                    }
                }
                $content = $modifiedContent;
                $rssGenerator->addItem(
                    $title,
                    $content,
                    mb_substr(strip_tags($content), 0, 100),
                    [$cats[($i + 1) % count($cats)]]
                );
            }
            $rssGenerator->saveToFile($filePath);
            echo "page:{$k} Processed " . count($items) . ' items.' . PHP_EOL;
        }

        echo 'Processing complete.' . PHP_EOL;
    }

    static function generateImageList($directory, $outputFile, $formatPath = "/static/imgs/")
    {
        if (!is_dir($directory)) {
            echo "Invalid directory: $directory" . PHP_EOL;
            return;
        }

        $images = scandir($directory);
        unlink($outputFile);

        foreach ($images as $image) {
            if (trim($image, '.') != "") {
                file_put_contents($outputFile, $formatPath . $image . PHP_EOL, FILE_APPEND);
            }
        }

        print_r($images);
    }
}
// 辅助函数：生成 WordPress 友好的 URL slug
function sanitize_title($title)
{
    $title = preg_replace('/[^a-z0-9\-]/', '-', strtolower($title));
    $title = preg_replace('/-+/', '-', $title);
    return trim($title, '-');
}

// 使用示例
// $rssGenerator = new WordPressRSSGenerator(
//     'https://gitee.com/xiongzaixxx', 
//     'free wordpress template', 
//     'free wordpress template by xiongzai'
// );

// 添加作者
// $rssGenerator->addAuthor('admin', 'admin@example.com', '管理员', '管理', '员');
// $rssGenerator->addAuthor('zhangsan', 'zhangsan@example.com', '张三');
// $rssGenerator->addAuthor('xiongzai', 'cnxiongzai@icloud.com', 'xiongzai');

// 添加分类
// $rssGenerator->addCategory('技术', 'tech', '技术相关文章');
// $rssGenerator->addCategory('编程', 'programming', '编程相关文章');
// $rssGenerator->addCategory('生活', 'life', '生活相关文章');

// 添加标签
// $rssGenerator->addTag('PHP', 'php', 'PHP相关文章');
// $rssGenerator->addTag('WordPress', 'wordpress', 'WordPress相关文章');
// $rssGenerator->addTag('日常', 'daily', '日常随笔');
// $rssGenerator->addTag('随笔', 'essay', '生活随笔');

// 添加示例文章
// $rssGenerator->addItem(
//     '第aaaaaaaaaaa一篇示sssfasdfasd例文章',
//     '<p>这是文章的内容，可以包含HTML标签。</p><p>第二段落内容。</p>',
//     '这是文章的摘要',
//     ['技术', '编程'],
//     ['PHP', 'WordPress'],
//     time() - 86400, // 发布时间（1天前）
//     '张三'
// );

// D:\articles\inputs\date2025062401



// $rssGenerator->addItem(
//     '第ssssssssssssss二篇示sssffs例文章',
//     '<p>另一篇文章的内容。</p><ul><li>列表项1</li><li>列表项2</li></ul>',
//     '这是第二篇文章的摘要'
// );

// 生成并保存RSS文件
// $rssGenerator->saveToFile('wordpress-export.xml');

$directory = "/mnt/d/articles/inputs/date20250604/102";
$outputDir = '/mnt/d/work/wordpress/outputs';
$cats = [
    [
        'name' => 'مسابقة التوقعات',
        'nicename' => 'a1',
    ],
    [
        'name' => 'مالتيميديا',
        'nicename' => 'a2'
    ],
    [
        'name' => 'فانتازي',
        'nicename' => 'a3'
    ],
    [
        'name' => 'ريلز',
        'nicename' => 'a4'
    ],
    [
        'nicename' => 'a5',
        'name' => "الانتقالات"
    ],
    [
        'nicename' => 'a6',
        'name' => 'المباريات'
    ],
    [
        'nicename' => 'nocat',        
    ],
];
TxtFileProcessor::processTxtFiles($directory, $outputDir, $cats);
